export default {
	namespaced:true,
	state:()=>({
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations:{
		addToCart(state,goods){
			const findResult = state.cart.find((x)=> x.goods_id === goods.goods_id)
			
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
			console.log(state.cart)
		},
		//将购物车数据保持久化储存到本地
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateGoodState(state,goods){
			
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if(findResult){
				console.log('更新购物车触发')
				findResult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsCount(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		removeGoods(state,goods){
			state.cart = state.cart.filter(x => goods.goods_id !== x.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		//实现商品的全选/反选功能
		updateAllGoodsState(state,newState){
			state.cart.forEach(item => item.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
		
	},
	getters:{
		total(state){
			let c = 0
			state.cart.forEach(good => {
				c += good.goods_count
			})
			return c
		},
		//勾选的商品总数量
		checkedCount(state){
			// 先使用 filter 方法，从购物车中过滤器已勾选的商品
			  // 再使用 reduce 方法，将已勾选的商品总数量进行累加
			  // reduce() 的返回值就是已勾选的商品的总数量
			return state.cart.filter(x => x.goods_state).reduce((total,item)=> total += item.goods_count,0)
		},
		//已勾选商品的总价
		checkedGoodsAmount(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
		}
	}
}